package com.followerback.resources;

import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.followerback.model.TwitterProfile;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import twitter4j.Twitter;
import twitter4j.auth.AccessToken;

@Path("/user")
public class UserResource extends Resource {

	private static final Logger logger = Logger.getLogger(UserResource.class.getName());
	
	@Path("/followers")
	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public Response getFollowers(@Context HttpServletRequest servletRequest) {
		
		
		/* Initial stuff */
		logger.info("Entering getFollowers");
		long methodStartTime = System.currentTimeMillis();
		HttpSession httpSession = servletRequest.getSession(true);
		AccessToken accessToken = (AccessToken)httpSession.getAttribute("accessToken");
		if(accessToken == null) {
			String errorReason = "Missing required params";
			logger.severe(errorReason);
			return Response.serverError().build();
		}
		Objectify objectify = ObjectifyService.begin();
		Twitter twitter = twitterFactory.getInstance();
		twitter.setOAuthAccessToken(accessToken);
		
		
		/* Get Followers */
		// get follower IDS
		List<Long> followerIDs = getFollowerIDs(twitter, null);
		
		// find twitter profile
		long userID = accessToken.getUserId();
		TwitterProfile twitterProfile = objectify.query(TwitterProfile.class).filter("userID", userID)
				.get();
		if(twitterProfile == null) {
			String errorReason = "Twitter profile not found";
			logger.severe(errorReason);
			return Response.serverError().entity("Are you signed in?").build();
		}
		
		// save followers
		postToSaveFollowers(twitterProfile.getId());
		
		
		/* End Stuff */
		logger.info("Exiting getFollowers in " +(System.currentTimeMillis() - methodStartTime)/1000d+ " secs");
		return Response.ok(""+followerIDs.size()).build();
	}
}
